package com.only4play.common.handler;

import com.only4play.common.constants.ErrorCodeEnum;
import com.only4play.common.exception.ApplicationException;
import com.only4play.common.model.GeneralResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * ApplicationExceptionHandler
 *
 * @author liyuncong
 * @date 2023/11/20 16:04
 **/
@Slf4j
@RestControllerAdvice
public class ApplicationExceptionHandler {

    @ExceptionHandler(value = {Exception.class, Throwable.class})
    public GeneralResponse<ErrorCodeEnum> handlerException(Exception exception) {
        exception.printStackTrace();
        if (exception instanceof ApplicationException) {
            int code = ((ApplicationException) exception).getErrorCodeEnum().getCode();
            String message = exception.getMessage();
            log.error("[全局异常拦截]ApplicationException: errorCode {},errorMessage {}",
                code, message);
            return GeneralResponse.of(code, message, null);
        } else {
            Integer code = ErrorCodeEnum.SERVER_ERROR.getCode();
            String message = ErrorCodeEnum.SERVER_ERROR.getMessage();
            log.error("[全局异常拦截]Exception: errorMessage {}", exception.getMessage());
            return GeneralResponse.of(code, message, null);
        }
    }
}
